package com.blogs.service;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Map;


import com.blogs.entity.AppConfig;
import com.blogs.entity.Author;
import com.blogs.entity.MsgEntity;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

public class GetAuthorSearch {
	public interface IMsgCallBack {
		public void onSuccess(ArrayList<Author> feedList);
		public void onFailed();
	}
	private String url="";
	private GetMsgTask timeLine;
    private IMsgCallBack callback;
    public GetAuthorSearch(String key,IMsgCallBack callback) {
		// TODO Auto-generated constructor stub
    	this.callback=callback;
		timeLine=new GetMsgTask(taskCallBack);
    	try {
			key=URLEncoder.encode(key,"utf-8");
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    	url=AppConfig.GET_AUTHOR_SEARCH;
    	url=url.replace("{0}", key);
	}
    public void loadData()
	{
		timeLine.execute(url);
	}
    private GetMsgTask.onTaskCallBack taskCallBack=new GetMsgTask.onTaskCallBack() {
    	public void onSuccess(String result) {
    		// TODO Auto-generated method stub
    		GsonBuilder builder = new GsonBuilder();
			Gson gson = builder.create();
			MsgEntity<ArrayList<Object>> msg=null;
			try
			{
				msg=gson.fromJson(result,MsgEntity.class);
			}
			catch(Exception e)
			{
				callback.onFailed();
				return;
			}
			if(msg.op.equals(""))
			{
				callback.onFailed();
				return;
			}
			ArrayList<Author> authors=new ArrayList<Author>();
			Iterator<Object> iterator = msg.data.iterator();
			while (iterator.hasNext()) 
			{
				Map<String, Object> objs = (Map<String, Object>) iterator.next();
				Author author = new Author(objs);
				authors.add(author);
			}
			callback.onSuccess(authors);
    	}
    	public void onFailed() {
    		// TODO Auto-generated method stub
    		callback.onFailed();
    	}
    };
}
